package com.ruoyi.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.ruoyi.common.SFTPUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.domain.AutoConfig;
import com.ruoyi.mapper.AutoConfigMapper;
import com.ruoyi.service.AutoConfigService;
import org.apache.ibatis.reflection.invoker.Invoker;
import org.apache.maven.shared.invoker.*;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
/**
 * lhp
 * 2024/8/26
 */
@Service
public class AutoConfigServiceImpl extends ServiceImpl<AutoConfigMapper, AutoConfig> implements AutoConfigService {
    @Override
    public AjaxResult topackage(AutoConfig autoConfig) {
        if(ObjectUtil.isEmpty(autoConfig.getId())){
            return AjaxResult.error("数据为空");
        }
        AutoConfig byId = this.getById(autoConfig.getId());
        InvocationRequest request = new DefaultInvocationRequest();
        request.setPomFile(new File(byId.getPomPath()));
        request.setGoals(Collections.singletonList("package"));
        DefaultInvoker invoker = new DefaultInvoker();
        invoker.setMavenHome(new File(byId.getMavenHomePath()));
        try {
            InvocationResult result = invoker.execute(request);
            int exitCode = result.getExitCode();
            System.out.println("退出码:"+exitCode);
            if (0==exitCode){
                return AjaxResult.success("构建成功");
            }else{
                return AjaxResult.error("构建失败");
            }
        } catch (MavenInvocationException e) {
            e.printStackTrace();
        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult add(AutoConfig autoConfig) {
        if(ObjectUtil.isEmpty(autoConfig.getId())){
            autoConfig.setId(IdUtil.getSnowflakeNextIdStr());
        }
        this.saveOrUpdate(autoConfig);
        return AjaxResult.success();
    }

    @Override
    public List<AutoConfig> getlist(AutoConfig autoConfig) {
        List<AutoConfig> list = this.query().list();
        return list;
    }

    @Override
    public AjaxResult toupload(AutoConfig autoConfig) {
        if(ObjectUtil.isEmpty(autoConfig.getId())){
            return AjaxResult.error("数据为空");
        }
        AutoConfig byId = this.getById(autoConfig.getId());
        SFTPUtil.sftpUpload(byId.getJarUploadPath(),byId.getJarPath(),byId.getHost(), byId.getPort(),byId.getUser(),byId.getPassword());
        return AjaxResult.success("上传成功");
    }

    @Override
    public AjaxResult restart(AutoConfig autoConfig) {
        if(ObjectUtil.isEmpty(autoConfig.getId())){
            return AjaxResult.error("数据为空");
        }
        AutoConfig byId = this.getById(autoConfig.getId());
            try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(byId.getUser(), byId.getHost(), byId.getPort());
        session.setPassword(byId.getPassword());

        // Avoid asking for key confirmation
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);

        session.connect();

        Channel channel = session.openChannel("exec");
        String cd=byId.getCdPathCode();
        String restart=byId.getRestartCode();
        String command=cd+";"+restart;
        ((ChannelExec) channel).setCommand(command);

        InputStream in = channel.getInputStream();
        OutputStream out = channel.getOutputStream();

        channel.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        channel.disconnect();
        session.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
        return AjaxResult.success("重启成功");
    }

    @Override
    public AjaxResult deleteDate(AutoConfig autoConfig) {
        if(ObjectUtil.isEmpty(autoConfig.getId())){
            return AjaxResult.error("数据为空");
        }
        this.removeById(autoConfig.getId());
        return AjaxResult.success("删除成功");
    }

//    public static void main(String[] args) {
//        InvocationRequest request = new DefaultInvocationRequest();
//        request.setPomFile(new File("D:\\code\\quick-master\\quick-master\\pom.xml"));
//        request.setGoals(Collections.singletonList("install"));
//        DefaultInvoker invoker = new DefaultInvoker();
//        invoker.setMavenHome(new File("D:\\java\\apache-maven-3.8.4"));
//        try {
//            InvocationResult result = invoker.execute(request);
//            int exitCode = result.getExitCode();
//            System.out.println("退出码:"+exitCode);
//            if (0==exitCode){
//                System.out.println("构建成功");
//            }else{
//                System.out.println("构建失败");
//            }
//        } catch (MavenInvocationException e) {
//            e.printStackTrace();
//        }
//    }

    private static final String HOST = "192.168.200.**********";
    private static final String USER = "root";
    private static final String PASSWORD = "11111111";
    private static final int PORT = 22; // SSH default port

//    public static void main(String[] args) {
////    SFTPUtil.sftpUpload("/home/ruoyi-test/project","D:\\newcode\\ruoyi-copy\\ruoyi-admin\\target\\ruoyi-test.jar","192.168.200.113",22,"root","11111111");
//    try {
//        JSch jsch = new JSch();
//        Session session = jsch.getSession(USER, HOST, PORT);
//        session.setPassword(PASSWORD);
//
//        // Avoid asking for key confirmation
//        Properties config = new Properties();
//        config.put("StrictHostKeyChecking", "no");
//        session.setConfig(config);
//
//        session.connect();
//
//        Channel channel = session.openChannel("exec");
//        ((ChannelExec) channel).setCommand("cd /home/ruoyi-test/project; ./ry.sh restart");
//
//        // Redirect the I/O streams
//        InputStream in = channel.getInputStream();
//        OutputStream out = channel.getOutputStream();
//
//        channel.connect();
//
//        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//        String line;
//        while ((line = reader.readLine()) != null) {
//            System.out.println(line);
//        }
//
//        channel.disconnect();
//        session.disconnect();
//    } catch (Exception e) {
//        e.printStackTrace();
//    }
//}




        public static void main(String[] args) {
            String projectPath = "D:\\code\\quick-ui-master\\quick-ui-master"; // 替换为你的Vue项目路径
            String npmPath = "D:\\tools\\node\\npm.cmd"; // 替换为实际路径

            try {
                // 运行Vue CLI的构建命令
                ProcessBuilder vueBuildBuilder = new ProcessBuilder(npmPath, "run", "build:prod");
                vueBuildBuilder.directory(new java.io.File(projectPath));
                Process vueBuildProcess = vueBuildBuilder.start();

                // 读取构建过程的输出
                BufferedReader reader = new BufferedReader(new InputStreamReader(vueBuildProcess.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
                int exitCode = vueBuildProcess.waitFor();
                System.out.println("Process exited with code: " + exitCode);

                if (exitCode == 0) {
                    System.out.println("Vue.js project packaged successfully.");
                } else {
                    System.out.println("Vue.js project packaging failed.");
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }


}
